<?php

namespace app\api\controller\v1;

use think\Db;
use think\Request;

class Rights extends Comment
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        switch($id)
        {
            case 'list':
                $data = Db::name('permission')
                     ->alias('p')
                     ->join('permission_api pa','p.ps_id = pa.ps_id')
                     ->field('p.ps_id as id,p.ps_name as authName,p.ps_level as level,p.ps_pid as pid,pa.ps_api_path as path')
                     ->select();
                break;
            case 'tree':
                $list = Db::name('permission')
                    ->alias('p')
                    ->join('permission_api pa','p.ps_id = pa.ps_id')
                    ->field('p.ps_id as id,p.ps_name as authName,p.ps_pid as pid,pa.ps_api_path as path')
                    ->select();

                return $this->getTree($list);
                break;

            default:
                return $this->out([],'输入参数有误',422);
        }

        if(empty($data)){
            return $this->out([],'获取权限列表失败',400);
        }

        return $this->out($data,'获取权限列表成功',200);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $rightId
     * @param int $roleId
     * @return \think\Response
     */
    public function delete($roleId,$rightId)
    {
        $roles = Db::name('role')
            ->where('role_id',$roleId)
            ->field('ps_ids')
            ->find();

        //获取删除权限后的新角色权限

        $ra = [];  //新角色权限列表

        foreach($roles as $key => $value){
            $ra = explode(',',$value);
        }

        foreach($ra as $key => $value){
            if($value === $rightId){
                array_splice($ra,$key,1);
            }
        }

        //将新角色权限数组拼接成字符串

        $PsIds = implode(",",$ra);

        //更新新权限
        $res = Db::name('role')
            ->where('role_id',$roleId)
            ->update(['ps_ids' => $PsIds]);

        if(empty($res)){
            return $this->out('无此权限，删除失败');
        }


        $list = Db::name('permission')
            ->alias('p')
            ->join('permission_api pa','p.ps_id = pa.ps_id')
            ->field('p.ps_id as id,p.ps_name as authName,p.ps_pid as pid,pa.ps_api_path as path')
            ->select();

        return $this->delAuth($list,$ra);
    }
}
